/* eslint-disable global-require */
import ElEditable from '@components/el-editable';
import {
  orderCommonFindOrderStatus, // 医院订单管理-订单状态集
  orderCommonQueryOrderInfo, // 医院订单管理-订单基本信息
  commerceGetOrderFlow,
  stockBatchList,
  orderProductList,
  getOrderDeliverList,
  findPaymentByOrderId,
  getOrderDeliverDetailList,
  getOrderLogistics,
  orderCancelProductList,
  orderGetAppendInfo,
  // findStockStatus,
  returnStatus
} from '@api/m_mall_web_v1.js';
import {
  COLUMNS,
  DELIVERY_ORDER_COLUMNS,
  RECEIVE_COLUMNS,
  RECEIVE_COORDINATION,
  SHIPPING_INFORMATION,
  PAY_INFO,
  CANCEL_COLUMNS,
  STOCK_TYPE
} from './index.const';
// eslint-disable-next-line import/extensions
import step from '~/modules/step';

export default {
  components: {
    ElEditable,
    step
  },
  inject: ['apiMMallWeb'],
  data() {
    return {
      orderTypeData: {
        '51': 'wholesale',
        '52': 'consign'
      },
      // text: "(去应付账单管理支付)",
      // timeOut: '00:00:00',
      // showTimeOut: true,
      activeStatus: 1,
      STEP_LIST: [
        {
          finishSrc: require('@assets/img/dingdantijiao-icon@2x.png'),
          waitSrc: require('@assets/img/dingdantijiao-icon@2x.png')
        },
        {
          finishSrc: require('@assets/img/yifahuo-icon@2x.png'),
          waitSrc: require('@assets/img/yifahuo-icon1@2x.png')
        },
        {
          finishSrc: require('@assets/img/shouhuo-icon@2x.png'),
          waitSrc: require('@assets/img/shouhuo-icon1@2x.png')
        },
        {
          finishSrc: require('@assets/img/yiwancheng-icon@2x.png'),
          waitSrc: require('@assets/img/yiwancheng-icon1@2x.png')
        }
      ],
      stepList: [],
      lastTimeDot: require('@assets/img/gaoling-icon@2x.png'),
      activeTimeImg: require('@assets/img/dangqianzhuangtai-icon@2x.png'),
      timeList: [],
      currentPage: 1,
      pageSize: 20,
      receivCurrentPage: 1,
      receivPageSize: 20,
      receivData: {},
      rowData: {},
      receivDataLoading: false,
      tableLoading: false,
      payload: {},
      dialogVisible: false,
      PAY_INFO, // 支付信息
      COLUMNS,
      CANCEL_COLUMNS,
      RECEIVE_COORDINATION, // 收货信息表头
      RECEIVE_COLUMNS, // 收货详情表头
      DELIVERY_ORDER_COLUMNS, // 出库单表头
      SHIPPING_INFORMATION, // 配送信息表头
      STOCK_TYPE,
      logisticsData: [],
      orderDetail: {},
      orderId: '',
      orderCode: '',
      orderDetailId: '',
      orderType: 1,
      busModel: 1,
      newBusModel: '',
      activeName: 'first',
      order_tab: [],
      stepData: [],
      stepData_offline: [],
      stepStr_offline: [],
      stockBatchData: [],
      supplierVo: {},
      addressResDto: {},
      orderAppendPOS: [],
      payDetailData: [],
      orderIdReturn: '',
      orderCodeReturn: '',
      orderIdExchange: '',
      orderCodeExchange: '',
      // 取消产品列表
      cancelTableLoading: false,
      cancelPayload: {},
      cancelContent: [],
      cancelCurrentPage: 1,
      cancelPageSize: 20,
      returnStutas: '', // 退货状态
      exchangeStutas: '' // 换货状态
    };
  },
  created() {
    this.orderId = this.$route.query.orderId;
    this.orderDetailId = this.$route.query.orderDetailId;
    this.orderCode = this.$route.query.orderCode;
    // this.setTime()

    // 获取步骤条数据
    this.getStepList();
    // 退货/换货按钮展示

    // 根据id获取列表详情
    this.$axios
      .$post(orderCommonQueryOrderInfo, {
        orderId: this.orderId
      })
      .then(res => {
        if (res.code === '0' && res.payload) {
          this.supplierVo = res.payload.supplierVo;
          this.addressResDto = res.payload.addressResDto;
          this.orderAppendPOS = res.payload.orderAppendPOS;
          this.orderDetail = {
            ...res.payload,
            hospitalName: res.payload.contractVo.hospitalName,
            hospitalCode: res.payload.contractVo.hospitalCode
          };
          this.newBusModel = res.payload.busModel;
          console.log();
          this.orderDetailId = res.payload.orderDetailId;
          this.orderIdReturn = res.payload.orderIdReturn;
          this.orderCodeReturn = res.payload.orderCodeReturn;
          this.orderIdExchange = res.payload.orderIdExchange;
          this.orderCodeExchange = res.payload.orderCodeExchange;
          this.getAppendInfo(res.payload.contractVo);
          this.getList(res.payload.orderDetailId);
          this.getCancelList(res.payload.orderDetailId);
        }
      });
    // 库存配位
    this.$axios
      .$post(stockBatchList, {
        orderId: this.orderId,
        page: 1,
        pageSize: 99999
      })
      .then(res => {
        if (res.code === '0' && res.payload.content) {
          this.stockBatchData = res.payload.content;
        }
      });
  },
  async mounted() {
    // const obj = {
    //   b: 'b'
    // }
    // obj.a = {
    //   a: 'a',
    //   c: undefined
    // }
    // // obj.a.b = obj
    // console.log(obj, 'obj')
    // let targert = JSON.parse(JSON.stringify(obj))
    // console.log(targert, 'target')
    // function deepClone (val) {
    //   return new Promise(resolve => {
    //     let {port1, port2} = new MessageChannel()
    //     port1.postMessage(val)
    //     port2.onmessage = data => resolve(data)
    //   })
    // }
    // deepClone(obj).then(res => {
    //   console.log(res, 'deep')
    // })
    // await this.getReturnStatus()
    // let arr = [];
    // if(this.returnStutas === 1){
    //   arr.push({type: 'primary', disabled: true, val: '退货中', handle: this.returning})
    // }
    // else if(this.returnStutas === 2){
    //   arr.push({type: 'primary', val: '申请退货', handle: this.applyForReturn})
    // }
    // if(this.exchangeStutas === 1){
    //   arr.push({type: 'primary', disabled: true, val: '换货中', handle: this.exchangeing})
    // }
    // else if(this.exchangeStutas === 2){
    //   arr.push({type: 'primary', val: '申请换货', handle: this.applyForExchange})
    // }
    // let btn = {
    //   type: 'btn',
    //   arr
    // }
    // this.$store.commit('changeLayoutHandle', btn)
    const btn = {
      type: 'btn',
      arr: []
    };
    btn.arr.push({
      type: 'primary',
      val: '再来一单',
      handle: this.goAdd
    });
    this.$store.commit('changeLayoutHandle', btn);
  },
  methods: {
    // 再来一单
    goAdd() {
      this.$router.push({
        path: `/hospital-purchase-order/${
          this.orderTypeData[this.newBusModel]
        }/add`,
        query: {
          orderId: this.orderId,
          reAdd: true
        }
      });
    },
    // 退货/换货按钮展示
    getReturnStatus() {
      const params = {
        orderCode: this.orderCode
      };
      return this.$axios.$post(returnStatus, params).then(res => {
        if (res.code === '0') {
          this.returnStutas = res.payload.returnStutas;
          this.exchangeStutas = res.payload.exchangeStutas;
        }
        return Promise.resolve(res);
      });
    },
    // 附加信息转译
    getAppendInfo(obj) {
      this.$axios
        .$post(orderGetAppendInfo, {
          productLineCode: obj.productLineCode,
          vendorNum: obj.supplierCode,
          busModel: 1,
          page: 1,
          pageSize: 9999
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.orderAppendPOS.forEach(item => {
              const newItem = item;
              res.payload.forEach(it => {
                if (newItem.attributeName === it.attributeName) {
                  const list = it.valueRange ? JSON.parse(it.valueRange) : [];
                  list.forEach(val => {
                    if (val.value === newItem.attributeValue) {
                      newItem.attributeValue = val.label;
                    }
                  });
                }
              });
            });
          }
        });
    },
    // 获取两个状态流转接口
    getStepList() {
      this.stepList = [];
      this.$axios
        .$post(orderCommonFindOrderStatus, {
          orderId: this.orderId
        })
        .then(res => {
          if (res.code === '0' && res.payload.orderStatusInfoVO) {
            const list = res.payload.orderStatusInfoVO;
            // 利用find返回true停止遍历的特性
            list.find((item, index) => {
              Object.assign(this.STEP_LIST[index], item);
              this.stepList.push(this.STEP_LIST[index]);
              return item.name === '已取消';
            });
            const index = this.stepList.findIndex(item => item.status === '0');
            this.activeStatus =
              index === -1 ? this.stepList.length - 1 : index - 1;
          } else {
            this.stepList = [];
          }
        })
        .catch(() => {
          this.stepList = [];
        });
      this.$axios
        .$post(commerceGetOrderFlow, {
          orderId: this.orderId
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            const list = res.payload[0].flowVos;
            this.timeList = list;
          } else {
            this.timeList = [];
          }
        })
        .catch(() => {
          this.timeList = [];
        });
      // this.$axios.$post(findStockStatus, {
      //   orderId: this.orderId
      // }).then(res => {
      //   if (res.code === '0' && res.payload) {
      //     let data = res.payload.orderStatusInfoVO
      //     let arr = []
      //     let newArr = []
      //     data.map(item => {
      //       if (Number(item.lineNum) === 1) {
      //         arr.push(item)
      //       } else {
      //         newArr.push(item)
      //       }
      //     })
      //     arr.sort(function (a, b) {
      //       return a.orderStatus - b.orderStatus
      //     });
      //     this.stepData_offline.push(arr)
      //     if (newArr.length) {
      //       let num = newArr.length / 2
      //       for (let i = 1; i <= num; i++) {
      //         let itemArr = []
      //         newArr.map(item => {
      //           if (Number(item.lineNum) === i + 1) {
      //             itemArr.push(item)
      //           }
      //         })
      //         itemArr.sort(function (a, b) {
      //           return a.orderStatus - b.orderStatus
      //         });
      //         this.stepData_offline.push(itemArr)
      //       }
      //     }
      //     let str = res.payload.remark ? res.payload.remark.split(',') : []
      //     str.map(item => {
      //       if (this.STOCK_TYPE[item]) {
      //         this.stepStr_offline.push(this.STOCK_TYPE[item])
      //       }
      //     })
      //   }
      // })
    },
    // 表格添加高亮
    // eslint-disable-next-line consistent-return
    tableRowClassName({ row }) {
      if (row.shortSupplyCount) {
        // if (row.productCount > row.confirmCount) {
        return 'bgHeight';
        // }
      }
    },
    // 订单详情采购产品分页列表
    getList() {
      this.tableLoading = true;
      this.$axios
        .$post(orderProductList, {
          orderDetailId: this.orderDetailId,
          page: this.currentPage,
          pageSize: this.pageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.payload = res.payload;
          }
          this.tableLoading = false;
        });
    },
    // 订单详情采购产品分页列表分页器
    reloadProductData(val) {
      this.currentPage = val.number;
      this.pageSize = val.size;
      this.getList();
    },
    // 取消产品分页器
    cancelReloadProductData(val) {
      this.cancelCurrentPage = val.number;
      this.cancelPageSize = val.size;
      this.getCancelList();
    },
    // 获取取消的产品列表
    getCancelList() {
      this.cancelTableLoading = true;
      this.$axios
        .$post(orderCancelProductList, {
          orderDetailId: this.orderDetailId,
          page: this.cancelCurrentPage,
          pageSize: this.cancelPageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload.content) {
            this.cancelPayload = res.payload;
            this.cancelContent = res.payload.content;
          }
          this.cancelTableLoading = false;
        });
    },
    // 底部tab切换调用不同接口
    handleClick(tab) {
      if (tab.name === 'fourth') {
        this.getOrderDeliverList();
      }
      if (tab.name === 'second') {
        this.getPayment();
      }
      if (tab.name === 'third') {
        this.getLogistics();
      }
    },
    // 支付信息
    getPayment() {
      this.$axios
        .$get(`${findPaymentByOrderId}?orderId=${this.orderId}`)
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.payDetailData = [res.payload];
          }
        });
    },
    // 配送信息
    getLogistics() {
      this.$axios
        .$post(getOrderLogistics, {
          orderCode: this.orderDetail.orderCode
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.logisticsData = res.payload;
          }
        });
    },
    // 收货信息列表
    getOrderDeliverList() {
      this.$axios
        .$get(`${getOrderDeliverList}?orderCode=${this.orderDetail.orderCode}`)
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.order_tab = res.payload;
          }
        });
    },
    showLog(row) {
      this.dialogVisible = true;
      this.rowData = row;
      this.getReceivList();
    },
    // 收货信息-详情列表分页器
    reloadReceiv(val) {
      this.receivCurrentPage = val.number;
      this.receivPageSize = val.size;
      this.getReceivList();
    },
    // 收货信息-详情列表
    getReceivList() {
      this.receivDataLoading = true;
      this.$axios
        .$post(getOrderDeliverDetailList, {
          deliverCode: this.rowData.deliverCode,
          page: this.receivCurrentPage,
          pageSize: this.receivPageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.receivData = res.payload;
          }
          this.receivDataLoading = false;
        });
    },
    // 退货中页面跳转
    returning() {
      this.$router.push({
        path: '/after-sale/order-management/returnDetails',
        query: {
          orderId: this.orderIdReturn,
          orderCode: this.orderCodeReturn
        }
      });
    },
    // 申请退货页面跳转
    applyForReturn() {
      this.$router.push({
        path: '/purchase-order/wholesale/list/return',
        query: {
          orderId: this.orderId,
          orderType: this.orderType
        }
      });
    },
    // 换货中页面跳转
    exchangeing() {
      this.$router.push({
        path: '/after-sale/order-management/returnDetails',
        query: {
          orderId: this.orderIdExchange,
          orderCode: this.orderCodeExchange
        }
      });
    },
    // 申请换货页面跳转
    applyForExchange() {
      this.$router.push({
        path: '/purchase-order/wholesale/list/exchange',
        query: {
          orderId: this.orderId,
          orderType: this.orderType
        }
      });
    }
  }
};
